﻿/* Picasa Wrapper - © 2013 Mattias Carlsson
 * Based on Pieter Roggemanns (the_roggy) batch file which can be found here:
 * http://productforums.google.com/forum/#!category-topic/picasa/picasa-for-windows/svsYxzyIskI
 * 
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.Diagnostics;
using System.IO;

namespace PicasaWrapper
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		private string _picasaExec = string.Empty;

		private string _picasaProfileENV = "PICASAPROFILEPATH";
		private string _picasaTempENV = "TEMPPATH";
		private string _userProfileENV = "USERPROFILE";
		//private string _picasaProfilePATH = @"M:\Photos\Picasa\Profile\Kareby";
		private string _picasaProfilePATH = @"C:\temp\picasa";
		private string _picasaTempPATH = @"\Appdata\Local";
		private string _picasaPID = @"\picasa_pid.txt";

		private Dictionary<string, string> _cmdArgs = new Dictionary<string, string>();

		ErrorDialog dlgError = new ErrorDialog();

		public MainWindow()
		{
			InitializeComponent();

			CheckArguments(Environment.GetCommandLineArgs());

			this.Loaded += MainWindow_Loaded;
		}

		/// <summary>
		/// Checks the command line arguments and skips them if they are not in the right format
		/// </summary>
		/// <param name="args">Array of strings containing all command line arguments</param>
		private void CheckArguments(string[] args)
		{
			if (args.Length > 2 && (args.Length % 2 == 1))
			{
				for (int index = 1; index < args.Length; index += 2)
				{
					_cmdArgs.Add(args[index], args[index + 1]);
				}

				_picasaProfilePATH = _cmdArgs["-profilepath"].ToString();
			}
			else
			{
				return;
			}
		}

		/// <summary>
		/// Does all the hard work once the main logo window is shown
		/// </summary>
		void MainWindow_Loaded(object sender, RoutedEventArgs e)
		{
			dlgError.Owner = this;

			if (File.Exists(_picasaProfilePATH + _picasaPID))
			{
				dlgError.ErrorMessage = "Google Picasa is already started by another user";
				dlgError.ShowDialog();
				Application.Current.Shutdown();
			}

			if (Environment.Is64BitOperatingSystem)
			{
				_picasaExec = @"C:\Program Files (x86)\Google\Picasa3\Picasa3.exe";
			}
			else
			{
				_picasaExec = @"C:\Program Files\Google\Picasa3\Picasa3.exe";
			}

			if (!CheckIfAppInstalled())
			{
				dlgError.ErrorMessage = "Could not find Google Picasa on the computer";
				dlgError.ShowDialog();
				Application.Current.Shutdown();
			}

			if (!VerifyFolders())
			{
				dlgError.ErrorMessage = "Could not create the necessary files for Google Picasa";
				dlgError.ShowDialog();
				Application.Current.Shutdown();
			}

			StartPicasa();
		}

		/// <summary>
		/// Checks if the needed folders exist and have the proper permissions. If they do not exist they are created.
		/// </summary>
		/// <returns>True if folders exist or if they were created successfully, false for everything else</returns>
		private bool VerifyFolders()
		{
			bool _folderSuccess = true;

			try
			{
				Directory.CreateDirectory(_picasaProfilePATH);
			}
			catch (Exception e)
			{
				if (e is IOException || e is UnauthorizedAccessException)
				{
					_folderSuccess = false;
				}
				else
				{
					throw;
				}
			}
			return _folderSuccess;
		}

		/// <summary>
		/// Checks if Google Picasa can be found on the computer
		/// </summary>
		/// <returns>True if found, false if not</returns>
		private bool CheckIfAppInstalled()
		{
			//string registryKey =
			//  @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";

			//using (Microsoft.Win32.RegistryKey key =
			//  Microsoft.Win32.Registry.LocalMachine.OpenSubKey(registryKey))
			//{
			//	var query = from a in
			//					key.GetSubKeyNames()
			//				let r = key.OpenSubKey(a)
			//				select new
			//				{
			//					Application = r.GetValue("DisplayName")
			//				};

			//	foreach (var item in query)
			//	{
			//		if (item.Application != null)
			//		{
			//			if (item.Application.ToString().Contains("Picasa"))
			//			{
			//				return true;
			//			}
			//		}
			//	}
			//	return false;
			//}

			if (File.Exists(_picasaExec))
			{
				return true;
			}

			return false;
		}

		/// <summary>
		/// Sets all the required environment variables, maintains a file to show that Google Picasa is running and starts Google Picasa
		/// </summary>
		private void StartPicasa()
		{
			// Set environment variables
			Environment.SetEnvironmentVariable(_picasaProfileENV, _picasaProfilePATH);
			Environment.SetEnvironmentVariable(_userProfileENV, _picasaProfilePATH);
			Environment.SetEnvironmentVariable(_picasaTempENV, _picasaProfilePATH + _picasaTempPATH);

			// Create a new process for Google Picasa
			Process p = new Process();
			p.StartInfo.FileName = _picasaExec;
			//p.StartInfo.Arguments = "/c dir *.cs";
			p.StartInfo.UseShellExecute = false;
			p.StartInfo.RedirectStandardOutput = true;

			this.Visibility = System.Windows.Visibility.Hidden;

			// Create the PID file before starting Google Picasa
			if (!File.Exists(_picasaProfilePATH + _picasaPID))
			{
				try
				{
					using (StreamWriter pidFile = new StreamWriter(_picasaProfilePATH + _picasaPID, false))
					{
						pidFile.WriteLine("Google Picasa started at " + DateTime.Now.ToString() + " by " + Environment.UserName + " on " + Environment.MachineName);
					}
				}
				catch (Exception ex)
				{
					if (ex is IOException || ex is DirectoryNotFoundException)
					{
						dlgError.ErrorMessage = "Could not create the Google Picasa PID file in " + _picasaProfilePATH + _picasaPID;
						dlgError.ShowDialog();
						Application.Current.Shutdown();
					}
					else
					{
						throw;
					}
				}

				// Start Google Picasa
				p.Start();
				p.WaitForExit();

				// Remove the PID file when Google Picasa exits
				if (File.Exists(_picasaProfilePATH + _picasaPID))
				{
					try
					{
						File.Delete(_picasaProfilePATH + _picasaPID);
					}
					catch (Exception ex)
					{
						if (ex is IOException || ex is DirectoryNotFoundException || ex is UnauthorizedAccessException)
						{
							this.Visibility = System.Windows.Visibility.Visible;
							dlgError.ErrorMessage = "Could not remove the Google Picasa PID file in " + _picasaProfilePATH + _picasaPID;
							dlgError.ShowDialog();
							Application.Current.Shutdown();
						}
						else
						{
							throw;
						}
					}
				}
			}
			Application.Current.Shutdown();
		}
	}
}
